package com.i_art_engineer.meigong.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.i_art_engineer.meigong.AppConsts;
import com.i_art_engineer.meigong.AppContext;
import com.i_art_engineer.meigong.AppHttpClient;
import com.i_art_engineer.meigong.R;
import com.i_art_engineer.meigong.base.FullScreenActivity;
import com.i_art_engineer.meigong.photo.MyImageView;
import com.i_art_engineer.meigong.photo.cache.BitmapLruCache;
import com.i_art_engineer.meigong.photo.cache.DiskLruCache;
import com.i_art_engineer.meigong.photo.cache.ACache;
import com.i_art_engineer.meigong.photo.cache.DiskLruCacheHelper;
import com.i_art_engineer.meigong.photo.crop.CropImageType;
import com.i_art_engineer.meigong.photo.crop.CropImageView;
import com.i_art_engineer.meigong.photo.filter.FilterTools;
import com.i_art_engineer.meigong.photo.filter.GPUImage;
import com.i_art_engineer.meigong.photo.filter.GPUImageFilter;
import com.i_art_engineer.meigong.photo.filter.GPUImageView;
import com.i_art_engineer.meigong.photo.filter.effect.GPUImageToneCurveFilter;
import com.i_art_engineer.meigong.photo.filter.effect.LomofiFilter;
import com.i_art_engineer.meigong.photo.filter.effect.TwoFilter;
import com.i_art_engineer.meigong.photo.font.FontSourceProcessor;
import com.i_art_engineer.meigong.photo.operate.ImageObject;
import com.i_art_engineer.meigong.photo.operate.OperateConsts;
import com.i_art_engineer.meigong.photo.operate.OperateUtils;
import com.i_art_engineer.meigong.photo.operate.ImageOperateView;
import com.i_art_engineer.meigong.photo.operate.TextObject;
import com.i_art_engineer.meigong.photo.text.MyImageView2;
import com.i_art_engineer.meigong.util.DimenUtils;
import com.i_art_engineer.meigong.util.DisplayUtils;
import com.i_art_engineer.meigong.util.ImageUtils;
import com.i_art_engineer.meigong.util.StringUtils;
import com.i_art_engineer.meigong.widget.AlertDialog;
import com.i_art_engineer.meigong.widget.CustomProgressDialog;
import com.i_art_engineer.meigong.widget.DragLinearView;
import com.i_art_engineer.meigong.widget.InputText;
import com.i_art_engineer.meigong.widget.SimpleSectionedGridAdapter;
import com.i_art_engineer.meigong.activity.WorksActivity.ImageAdapter;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

/**
 * 图片编辑界面
 */
public class PhotoEditorActivity extends FullScreenActivity {

    public static final String EXTRA_SELECTED_IMAGES = "selected_images";

    private ArrayList<String> photo_paths;  //初始图片路径
    //public static HashMap<String, Bitmap> photos = new HashMap<>();  //编辑后的图片:原图路径->编辑后的效果图

    private DiskLruCacheHelper mImgCache;
    private ACache mCache;
    private BitmapLruCache bitmapLruCache = null;
    private String currImagePath;
    private Bitmap cacheBitmap = null;
    private static long lastClickTime;

    private LinearLayout mPhotosView;

    private LinearLayout currThumb;

    private ImageAdapter mAdapter;

    private WaterImageAdapter mWaterAdater;

    private ArrayList<String> mStickers = new ArrayList<>();
    private ArrayList<Integer> mStickers_id = new ArrayList<>();
    private ArrayList<String> mStickersId = new ArrayList<>();
    //    private HashMap<String, Bitmap> mFilters = new HashMap<>();
//    private HashMap<String,ImageOperateView>  listItems=new HashMap<String,ImageOperateView>();
//    private HashMap<String,FrameLayout>listOperateArea=new HashMap<String,FrameLayout>();
    private HashMap<String, List<ImageObject>> list_object = new HashMap<String, List<ImageObject>>();
    private List<ImageObject> list_item = new ArrayList<ImageObject>();
    /**
     *
     */
    private FrameLayout operateArea;
    private LinearLayout operateParent;
    private InputText operateInput;
    private ImageOperateView operateView;
    private OperateUtils operateUtils;

    SeekBar filterSeekBar;

    /**
     * 文本编辑信息
     */
    private Typeface defaultFont;
    private int defaltFontColor;

    private String[] fontname = {
            "kaiti.ttf",
            "lishu.ttf",
            "song.ttf",
            "xihei.ttf",
            "xinwei.ttf",
            "youyuan.ttf"
    };
    /**
     * 贴图
     */
    private JSONArray imageArr;
    private JSONArray imageArrId;
    private GridView grid;
    private int stickerHeight;

    /**
     * 裁剪
     */
    private CropImageView cropView;

    /**
     * 滤镜
     */
    private GPUImageView mFilterView;
    private GPUImageView m1FilterView;
    private GPUImageFilter mFilter;
    private FilterTools.FilterAdjuster mFilterAdjuster;
    private GridView gridWater;

    private Resources res;

    /**
     * 主编辑区域
     */
    private FrameLayout ll_photo_editor;
    private ImageView iv_photo_real_image;

    private LinearLayout ll_photo_tools, ll_edit_area, ll_text_tools, ll_tietu_tools, ll_filter_tools,
            ll_watermark_tools, ll_crop_tools, ll_jigsaw_tools;


    // 文本编辑界面
    private LinearLayout ll_text_tools_area, ll_text_tools_sub_area, ll_text_tools_fonts, ll_text_tools_colors, ll_text_tools_phrases, ll_watermark_colors;

    // 其他编辑界面
    private LinearLayout ll_stickers_area, ll_filters_area, ll_watermarks_area, ll_crop_area, ll_share_area;

    private ScrollView ll_watermark_list;

    private LayoutInflater flater;
    private Handler handler;
    public static final int UPDATE_FILTER = 1200;
    public static final int SHOW_PICTURE = 1201;
    public static boolean is_can_update = true;
    public static final String PROCESSED = "processed";
    public HashMap<String, Boolean> list_used_processed = new HashMap<String, Boolean>();//保留当前编辑的图片时候使用编辑后的图片

    public boolean is_used_processed() {
        return list_used_processed.get(currImagePath);
    }

    public void setIs_used_processed(boolean is_used_processed) {
        list_used_processed.put(currImagePath, is_used_processed);
    }

    private interface CacheImageCallbackInterface {
        public void onImageLoaded(Bitmap image);
    }

    ;

    private interface LoadImageCallbackInterface {
        public Bitmap loadImage();
    }

    ;

    public static boolean is_first_create = true;
    public Bitmap bitmapToFilter;
    Bitmap curbmToFilter = null;
    private Target target;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_editor);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case UPDATE_FILTER:
                        if (is_can_update) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {

                                    long start_time = System.currentTimeMillis();
                                    is_can_update = false;

                                    Bitmap ori = mCache.getAsBitmap(ORIGBITMAP);
                                    if (ori != null && !ori.isRecycled())
                                        ProcessFilterProgress(ori, curbmToFilter);
                                    else
                                        Log.e("processfiter", "bp is null");

//                                    saveImageToGallery(curbm);
//                                    Bitmap ori=null;
//                                    if(operateView!=null)
//                                    {
//                                        if(bitmapToFilter!=null&&!bitmapToFilter.isRecycled())
//                                        {
//                                            Log.e("PhotoEditorActivity","no need to create bitmap");
//                                        }
//                                        if(bitmapToFilter==null) {
//                                            bitmapToFilter = operateView.getRetBmp(true);
//                                        }
//                                    }
//                                    Bitmap bp = toConformBitmap(curbm, bitmapToFilter, mprogress);
//                                    setFilterImage(bp);

                                    Log.e("PhotoEditorActivity", " filter time=" + (System.currentTimeMillis() - start_time));
                                    is_can_update = true;
                                }
                            }).start();
                        } else {
                            Log.e("PhotoEditorActivity", "update too fast!!!!!!!!!!");
                        }
                        break;
                    case SHOW_PICTURE:

                        break;

                }
                super.handleMessage(msg);
            }
        };

        // 加载图像列表
        Intent intent = getIntent();
        photo_paths = intent.getStringArrayListExtra(EXTRA_SELECTED_IMAGES);

        res = this.getResources();

        flater = LayoutInflater.from(this);
        defaultFont = Typeface.DEFAULT;
        defaltFontColor = res.getColor(R.color.default_text_color);
        operateUtils = new OperateUtils(this);
        mCache = AppContext.instance().getmCache();
        long start = System.currentTimeMillis();
        initViews();
        mdialog = createLoadingDialog(PhotoEditorActivity.this, "图片加载中");
        mdialog.show();
        initImageEditorView();
        initFilterEditorfirstView();

        long end = System.currentTimeMillis();
        Log.e("oncreate", "time=" + (end - start));
    }

    GPUImageFilter mfilterTwo = null;

    public void ProcessFilterProgress(Bitmap ori, Bitmap cur) {
//       if(mfilterTwo==null)
        {
            FilterTools.setBmp(ori);//相当于textture
            mfilterTwo = FilterTools.createFilterForType(PhotoEditorActivity.this, FilterTools.FilterType.TWO);
        }
        float contrast = mprogress / 100.0f;
        mFilterView.setImage(cur);
//       ((TwoFilter)mfilterTwo).setBmp(ori);
        ((TwoFilter) mfilterTwo).setmContrastLocation(contrast);
        mFilterView.setFilter(mfilterTwo);
        mFilterView.requestRender();
    }

    @Override
    protected void onResume() {
        freeFilterEditorView(true);
        if (operateView != null)
            operateView.setIs_can_edit(false);
        slideToolsArea(false);
        if (operateView != null) {
            setCurImage(new CacheImageCallbackInterface() {
                @Override
                public void onImageLoaded(Bitmap image) {
                    List<ImageObject> list = list_object.get(currImagePath);
                    if (list != null && list.size() > 0) {
                        operateView.setImgLists(list);
                    }
                }
            });
            Log.e("onResum", "onresume");
            if (!operateView.getFlag())
                operateView.setFlag(true);
        }
        super.onResume();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            freeFilterEditorView(true);
            if (operateView != null)
                operateView.setIs_can_edit(false);
            slideToolsArea(false);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    PhotoEditorActivity.this.finish();
                }
            },200);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        try
        {
            is_first_started = true;
//            operateView.setFlag(false);
            Bitmap bgm = operateView.getBgBmp();
            Bitmap retbg = operateView.getRetBmp();
            Bitmap resizebg = operateView.getResizeBmp();
            if (bgm != null && !bgm.isRecycled()) {
                bgm.recycle();
                bgm = null;
                System.gc();
                Log.e("bgm", "on destroy free bgm bitmap");
            }
            if (retbg != null && !retbg.isRecycled()) {
                retbg.recycle();
                retbg = null;
                System.gc();
                Log.e("bgm", "on destroy  free ret bitmap");
            }
            if (resizebg != null && !resizebg.isRecycled()) {
                resizebg.recycle();
                resizebg = null;
                System.gc();
                Log.e("bgm", " on destroy free resizebg bitmap");
            }
            for (int i = 0; i < photo_paths.size(); i++) {
                mCache.remove(PROCESSED + photo_paths.get(i));
                Log.e("ondestroy", "delete mached");
            }
            if (cacheBitmap != null && !cacheBitmap.isRecycled()) {
                cacheBitmap.recycle();
                cacheBitmap = null;
                System.gc();
            }
            if (newbmp != null && !newbmp.isRecycled()) {
                newbmp.recycle();
                newbmp = null;
            }
        }
        operateView = null;
        System.gc();
//        catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    /**
     * @param context
     * @param uniqueName 缓存文件夹名称，可以自定义。这里我们缓存的是bitmap，所以缓存文件夹名定义为：bitmap
     * @return
     * @description 获得磁盘缓存的路径
     * 当SD卡存在或SD卡不可被移除的时，就用getExternalCacheDir()方法来获取缓存路径，否则就调用getCacheDir()方法来获取缓存路径。
     * getExternalCacheDir()-> /sdcard/Android/data/<application
     * package>/cache getCacheDir() -> /data/data/<application package>/cache
     */
    private File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }

    private void initMemLruCache() {
        if (bitmapLruCache == null) {
            bitmapLruCache = new BitmapLruCache();
        }
    }

    /**
     * @description 初始化磁盘缓存
     */
    private void initCache() {
        try {
            File cacheDir = getDiskCacheDir(this, "photos");
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
                mImgCache = new DiskLruCacheHelper(this, cacheDir);
            } else {
                mImgCache = new DiskLruCacheHelper(this, cacheDir);
                for (String str : photo_paths) {
                    mImgCache.remove(str);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addBitmapToCache(final String key, final Bitmap bitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mCache.remove(key);
                mCache.put(key, bitmap);
                ;
            }
        }).start();

    }

    public Bitmap getBitmapFromDiskCache(final String key) {
        Bitmap mp = mCache.getAsBitmap(key);
        if (mp == null) {

            //先计算大小
            BitmapFactory.Options opts = new BitmapFactory.Options();
            try {
                mp = ImageUtils.getBitmapByPath(this, key, opts);
                final Bitmap finalMp = mp;
                mCache.put(key, finalMp);

            } catch (OutOfMemoryError e) {
                //
                Log.e("IART", "out of memory!!!!");
            }
        }

        return mp;
    }

    private static int computeInitialSampleSize(
            BitmapFactory.Options options,
            int minSideLength,
            int maxNumOfPixels
    ) {
        double w = options.outWidth;

        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));

        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;

        if (initialSize <= 8) {
            roundedSize = 1;

            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    private void asyncGetCacheImage(final String cacheImageKey, final CacheImageCallbackInterface callback) {
        new Thread() {
            public void run() {

                if (cacheBitmap == null)
                    cacheBitmap = getBitmapFromDiskCache(cacheImageKey);

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onImageLoaded(cacheBitmap);
                    }
                });
            }
        }.start();
    }

    private void asyncGetImage(final LoadImageCallbackInterface loadImageCallback, final CacheImageCallbackInterface callback) {
//        final Dialog dialog = new Dialog(this);
//        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        dialog.setContentView(new TextView(this));
//        dialog.setCancelable(false);
//        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
//        dialog.show();
        new Thread() {
            public void run() {
                try {
                    try {
                        final Bitmap bitmap = loadImageCallback.loadImage();

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onImageLoaded(bitmap);
                            }
                        });
                    } catch (OutOfMemoryError error) {
                        Toast.makeText(PhotoEditorActivity.this, "内存不足,请关闭其他程序", Toast.LENGTH_SHORT);
                    }
                } catch (Exception e) {

                }

//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            dialog.cancel();
//                        }
//                        catch (Exception e) {
//
//                        }
//                    }
//                });
            }
        }.start();
    }

    public void PrePareReadBitmapFromFile() {
        final ArrayList<String> list = photo_paths;
        Bitmap mp = null;
        for (int i = 1; i < list.size(); i++) {
            Bitmap bp = mCache.getAsBitmap(list.get(i));
            if (bp == null) {
                long start2 = System.currentTimeMillis();
                BitmapFactory.Options opts = new BitmapFactory.Options();
                try {
                    mp = ImageUtils.getBitmapByPath(this, list.get(i), opts);
                    long start = System.currentTimeMillis();
                    mCache.put(list.get(i), mp, 30 * ACache.TIME_DAY);
                    long end = System.currentTimeMillis();
                    Log.e("put time", "time=" + (end - start));

                } catch (OutOfMemoryError e) {
                    //
                    Log.e("IART", "out of memory!!!!");
                }

            } else {
                Log.e("photoedit", "no need read bitmap");
            }
        }
    }

    public void initViews() {
        // 返回按钮
        findViewById(R.id.btn_back).setOnClickListener(listener);
        findViewById(R.id.tv_PhotoSave).setOnClickListener(listener);

        currImagePath = photo_paths.get(0);


        initThumbViews(photo_paths, false);

        ll_photo_editor = (FrameLayout) findViewById(R.id.ll_photo_editor_view);//主图编辑区的layout
        iv_photo_real_image = (ImageView) findViewById(R.id.iv_photo_editor_final_image);//主图编辑区的显示imageview
        iv_photo_real_image.setVisibility(View.GONE);

        ll_photo_tools = (LinearLayout) findViewById(R.id.ll_photo_tools);//主功能区的layout
        ll_edit_area = (LinearLayout) findViewById(R.id.ll_edit_tools_area);//注功能区的二级编辑菜单container


        ll_text_tools = (LinearLayout) findViewById(R.id.ll_photo_txt_tools);//一级菜单
        ll_tietu_tools = (LinearLayout) findViewById(R.id.ll_photo_tietu_tools);
        ll_filter_tools = (LinearLayout) findViewById(R.id.ll_photo_filter_tools);
        ll_watermark_tools = (LinearLayout) findViewById(R.id.ll_photo_watermark_tools);
        ll_crop_tools = (LinearLayout) findViewById(R.id.ll_photo_crop_tools);
        ll_jigsaw_tools = (LinearLayout) findViewById(R.id.ll_photo_jigsaw_tools);
        ll_text_tools.setOnClickListener(listener);
        ll_tietu_tools.setOnClickListener(listener);
        ll_filter_tools.setOnClickListener(listener);
        ll_watermark_tools.setOnClickListener(listener);
        ll_crop_tools.setOnClickListener(listener);
        ll_jigsaw_tools.setOnClickListener(listener);
    }


    private void initGrid() {
        //屏幕宽度
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenHeight = dm.heightPixels;

        //设置grid高度
        int gridHeight = screenHeight - stickerHeight - DimenUtils.dp2px(PhotoEditorActivity.this, 65);
        LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) grid.getLayoutParams();
        linearParams.height = gridHeight;
        grid.setLayoutParams(linearParams);
        mAdapter = new ImageAdapter(PhotoEditorActivity.this, mStickersId);
        SimpleSectionedGridAdapter simpleSectionedGridAdapter = new SimpleSectionedGridAdapter(
                PhotoEditorActivity.this, mAdapter,
                R.layout.works_grid_item_header, R.id.header_layout, R.id.header);
        simpleSectionedGridAdapter.setGridView(grid);
        grid.setAdapter(simpleSectionedGridAdapter);
    }


    private void initGridWater() {
        //屏幕宽度
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenHeight = dm.heightPixels;

        //设置grid高度
        int gridHeight = screenHeight - 10 - stickerHeight - DimenUtils.dp2px(PhotoEditorActivity.this, 65);
        LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) gridWater.getLayoutParams();
        linearParams.height = gridHeight;
        gridWater.setLayoutParams(linearParams);

        mWaterAdater = new WaterImageAdapter(PhotoEditorActivity.this);
        SimpleSectionedGridAdapter simpleSectionedGridAdapter = new SimpleSectionedGridAdapter(
                PhotoEditorActivity.this, mWaterAdater,
                R.layout.works_grid_item_header, R.id.header_layout, R.id.header);
        simpleSectionedGridAdapter.setGridView(gridWater);
        gridWater.setAdapter(simpleSectionedGridAdapter);
    }

    public Dialog mdialog;

    /**
     * 得到自定义的progressDialog
     *
     * @param context
     * @param msg
     * @return
     */
    public Dialog createLoadingDialog(Context context, String msg) {

//        LayoutInflater inflater = LayoutInflater.from(context);
//        View v = inflater.inflate(R.layout.loading_dialog, null);// 得到加载view
//        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局
//        // main.xml中的ImageView
//        ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
//        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
//        // 加载动画
//        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
//                context, R.anim.loading_animation);
//        // 使用ImageView显示动画
//        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
//        tipTextView.setText(msg);// 设置加载信息
//
//        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog

        Dialog loadingDialog=new CustomProgressDialog(context,R.style.dialog);

        loadingDialog.setCancelable(false);// 不可以用“返回键”取消

//        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.FILL_PARENT,
//                LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
        return loadingDialog;

    }

    /**
     * 初始化缩略图
     */
    public void initThumbViews(ArrayList<String> paths, boolean isAppend) {
        mPhotosView = (LinearLayout) findViewById(R.id.ll_photos_thumb_list);
        int height = res.getDimensionPixelSize(R.dimen.photo_action_bar_thumb_height);
        int imgh = res.getDimensionPixelSize(R.dimen.photo_action_bar_thumb_img_height);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(height, height);
        lp.setMargins(0, 5, 0, 5);
        for (int i = 0; i < paths.size(); i++) {
            final LinearLayout thumb = (LinearLayout) flater.inflate(R.layout.list_item_photo, null);
            ImageView img = (ImageView) thumb.findViewById(R.id.image);
            ImageView jiantou = (ImageView) thumb.findViewById(R.id.jiantou);
            View mask = thumb.findViewById(R.id.mask);
            ImageView del = (ImageView) thumb.findViewById(R.id.delmark);

            if (currImagePath.equals(paths.get(i))) {
                mask.setVisibility(View.VISIBLE);
                jiantou.setVisibility(View.VISIBLE);
                img.setBackgroundColor(res.getColor(R.color.photo_thumb_selected_border_color));
                currThumb = thumb;
            }
            list_used_processed.put(paths.get(i), false);
            thumb.setTag(paths.get(i));
            thumb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    mdialog = ProgressDialog.show(PhotoEditorActivity.this, "图片加载", "正在加载，请稍等...", false);


                    synchronized (this) {
//                        if (mCache.getFile(currImagePath) == null) {
//                            Toast.makeText(PhotoEditorActivity.this, "请稍等", Toast.LENGTH_SHORT).show();
//                            return;
//                        }
                        if (mFilterView != null) {
                            Toast.makeText(PhotoEditorActivity.this, "请先保存滤镜效果", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        mdialog = createLoadingDialog(PhotoEditorActivity.this, "图片加载中");
                        mdialog.show();
                        String file = (String) thumb.getTag();
                        if(currImagePath.equals(file)){
                            mdialog.dismiss();
                        }
                        if (!currImagePath.equals(file)) {
                            View mask = thumb.findViewById(R.id.mask);
                            ImageView bg = (ImageView) thumb.findViewById(R.id.image);
                            ImageView jt = (ImageView) thumb.findViewById(R.id.jiantou);
                            jt.setVisibility(View.VISIBLE);
                            bg.setBackgroundColor(res.getColor(R.color.photo_thumb_selected_border_color));
                            mask.setVisibility(View.VISIBLE);
                            filterItem=0;
                            Bitmap bgm = null;
                            //暂停surfaceview，释放资源
                            if (operateView != null) {
                                operateView.setFlag(false);
                                try {
                                    Thread.sleep(100);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                operateView.ClearAllItem();
                                operateView.FreeBitmap();
                            }
                            Log.e("photoEditorActiviy", "after freebitmap");
                            currImagePath = file;
                            List<ImageObject> list = list_object.get(currImagePath);
                            operateView.setFlag(true);
                            initImageEditorView();

                            if (list != null && list.size() > 0) {
                                for (int i = 0; i < list.size(); i++)
                                    list.get(i).setSelected(false);
                                operateView.setImgLists(list);
                            }
                            if (currThumb != null) {
                                View oldMask = currThumb.findViewById(R.id.mask);
                                ImageView oldBg = (ImageView) currThumb.findViewById(R.id.image);
                                ImageView oldJt = (ImageView) currThumb.findViewById(R.id.jiantou);
                                oldJt.setVisibility(View.GONE);
                                oldBg.setBackgroundColor(res.getColor(R.color.default_action_bar_color));
                                oldMask.setVisibility(View.GONE);
                            }
                            currThumb = thumb;
                            slideToolsArea(false);
                            System.gc();

                        }
                    }
                }
            });
            del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String file = (String) thumb.getTag();
                    if (currImagePath != file) {
                        photo_paths.remove(file);
                        mCache.remove(file);
//                        mImgCache.remove(file);
                        mPhotosView.removeView(thumb);
                    }
                }
            });
            // 显示图片
            Picasso.with(this)
                    .load(new File(paths.get(i)))
                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                    .placeholder(R.drawable.tu)
                    .resize(imgh, imgh)
                    .centerCrop()
                    .into(img);

            thumb.setLayoutParams(lp);
            if (isAppend) {
                mPhotosView.addView(thumb, photo_paths.size());
                photo_paths.add(paths.get(i));
//                operateView.setBgBmp(mCache.getAsBitmap(currImagePath));
            } else
                mPhotosView.addView(thumb);
        }

        if (!isAppend) {
            final LinearLayout thumb = (LinearLayout) flater.inflate(R.layout.list_item_photo, null);
            ImageView img = (ImageView) thumb.findViewById(R.id.image);
            View mask = thumb.findViewById(R.id.mask);
            ImageView del = (ImageView) thumb.findViewById(R.id.delmark);
            thumb.setTag("");
            thumb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mFilterView != null) {
                        Toast.makeText(PhotoEditorActivity.this, "请先保存滤镜效果", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Intent intent = new Intent(PhotoEditorActivity.this, PhotoSelectorActivity.class);
                    // 是否显示拍摄图片
                    intent.putExtra(PhotoSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大可选择图片数量
                    intent.putExtra(PhotoSelectorActivity.EXTRA_SELECT_COUNT, AppConsts.PHOTO_SELECTOR_IMAGE_MAX_NUM);
                    // 选择模式
                    intent.putExtra(PhotoSelectorActivity.EXTRA_SELECT_MODE, PhotoSelectorActivity.MODE_MULTI);
                    // 已选择图片
                    intent.putExtra(PhotoSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, photo_paths);
                    intent.putExtra(PhotoSelectorActivity.EXTRA_APPEND_IMAGES_MODE, true);
                    startActivityForResult(intent, AppConsts.ACTIVITY_REQUEST_PHOTO_AGAIN_SELECTOR_IMAGE);
                }
            });
            mask.setVisibility(View.GONE);
            del.setVisibility(View.GONE);
            // 显示图片
            Picasso.with(this)
                    .load(R.drawable.tianjia)
                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                    .placeholder(R.drawable.tu)
                    .resize(imgh, imgh)
                    .into(img);
            thumb.setLayoutParams(lp);
            mPhotosView.addView(thumb);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConsts.ACTIVITY_REQUEST_PHOTO_AGAIN_SELECTOR_IMAGE) {
            if (resultCode == RESULT_OK) {
                //获取新增的图片
                ArrayList<String> newImgs = data.getStringArrayListExtra(PhotoSelectorActivity.EXTRA_RESULT);
                //TODO:
                initThumbViews(newImgs, true);

            }
        }
    }

    public void freeAllEditorViews(boolean isCancel) {
        freeImageEditorView(isCancel);
        freeCropEditorView(isCancel);
        freeFilterEditorView(isCancel);
    }

    public void showImagePreview(boolean isShow, boolean isRefresh) {
        if (isShow) {
            if (isRefresh) {
                asyncGetCacheImage(currImagePath, new CacheImageCallbackInterface() {
                    @Override
                    public void onImageLoaded(Bitmap image) {
                        iv_photo_real_image.setVisibility(View.VISIBLE);
                        iv_photo_real_image.setImageBitmap(image);
                    }
                });
            } else {
                asyncGetCacheImage(currImagePath, new CacheImageCallbackInterface() {
                    @Override
                    public void onImageLoaded(Bitmap image) {
                        iv_photo_real_image.setVisibility(View.VISIBLE);
                        iv_photo_real_image.setImageBitmap(image);
                    }
                });
            }

        } else {
            iv_photo_real_image.setVisibility(View.GONE);
        }
    }

    private void setCurImage(final CacheImageCallbackInterface opEndCallback) {
        asyncGetImage(new LoadImageCallbackInterface() {
            @Override
            public Bitmap loadImage() {

                Bitmap bmp = null;
                if (is_used_processed())
                    bmp = mCache.getAsBitmap(PROCESSED + currImagePath);
                if (bmp == null) {
                    bmp = mCache.getAsBitmap(currImagePath);
                    if (bmp == null) {
                        BitmapFactory.Options opts = new BitmapFactory.Options();
                        bmp = ImageUtils.getBitmapByPath(PhotoEditorActivity.this, currImagePath, opts);
                        mCache.put(currImagePath, bmp);
                    }
                }
                return bmp;
            }
        }, new CacheImageCallbackInterface() {
            @Override
            public void onImageLoaded(Bitmap image) {
                setImageToOperateView(image);
                if (opEndCallback != null) {
                    opEndCallback.onImageLoaded(image);
                }
                operateView.updateView();
                if (mdialog != null && mdialog.isShowing()) {
                    mdialog.dismiss();
                    mdialog = null;
                }
            }
        });
    }

    private void setImageToOperateView(Bitmap image) {

        operateView.setBgBmp(image);
        operateView.updateView();

    }

    /**
     * 初始化图片编辑界面: 文本/贴图/水印
     */
    public void initImageEditorView() {
        if (operateView == null) {
            operateView = new ImageOperateView(PhotoEditorActivity.this, null);
            operateArea = (FrameLayout) flater.inflate(R.layout.view_operate_area, null);//文字，贴图，水印的操作区
            operateParent = (LinearLayout) operateArea.findViewById(R.id.operate_view_parent);
            operateInput = (InputText) operateArea.findViewById(R.id.operate_text_input);


            setCurImage(null);

            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            operateView.setMultiAdd(true); //设置此参数，可以添加多个文字/图片
            operateView.setLayoutParams(layoutParams);
//            operateView.setFlag(true);
            operateParent.addView(operateView);

            ll_photo_editor.addView(operateArea);
//            listOperateArea.put(currImagePath,operateArea);
//            listItems.put(currImagePath, operateView);

        } else {
            setCurImage(null);
        }

    }

    public static boolean is_first_started = true;

    public void freeImageEditorView(boolean isCancel) {
        if (operateView != null) {
            // 保存处理结果
            if (!isCancel) {

//                if(operateView!=null) {
                //为了后面拼图使用
                final Bitmap bmp = operateView.getRetBmp();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mCache.remove(PROCESSED + currImagePath);
                        mCache.put(PROCESSED + currImagePath, bmp);
                    }
                }).start();

//                }
                List<ImageObject> listtmp = operateView.getTmpImgLists();
                if (listtmp != null && listtmp.size() > 0)
                    listtmp.clear();
                List<ImageObject> list = operateView.getImgLists();
                List<ImageObject> lst = list_object.get(currImagePath);
                if (lst == null) {
                    lst = new ArrayList<ImageObject>();
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            lst.add(list.get(i));
                            lst.get(i).setSelected(false);
                        }
                        list_object.put(currImagePath, lst);
                    }
                } else {
                    lst.clear();
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            lst.add(list.get(i));
                            lst.get(i).setSelected(false);
                        }
                    }
                }
            } else {
//                operateView.setFlag(true);
                List<ImageObject> list = operateView.getTmpImgLists();
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ImageObject io = list.get(i);
                        if (io != null) {
                            operateView.removeItem(io);
                        }
                    }
                }
//                list.clear();

            }
        }
        if (!operateView.getFlag())
            operateView.setFlag(true);
        System.gc();
    }

    /**
     * 初始化裁剪界面
     */
    public void initCropEditorView() {
        if (cropView == null) {
//            showImagePreview(false, false);
            cropView = new CropImageView(this);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
            );
            cropView.setLayoutParams(layoutParams);
            if (operateArea != null)
                ll_photo_editor.removeView(operateArea);
//            if(operateArea!=null)
//                operateArea.setVisibility(View.GONE);//设置成GONE，减少切换开支
            ll_photo_editor.addView(cropView);
            Bitmap bmp = operateView.getRetBmp();
            if (bmp != null && !bmp.isRecycled()) {
                cropView.setImageBitmap(bmp);
            } else
                cropView.setImageBitmap(getBitmapFromDiskCache(currImagePath));

            cropView.setGuidelines(CropImageType.CROPIMAGE_GRID_ON);// 触摸时显示网格
            cropView.setFixedAspectRatio(false);// 自由剪切
            //暂停surfaceview，释放资源
//            operateView.setFlag(false);
            operateView.FreeGarbageBitmap();
        }
    }

    /**
     * 释放裁剪界面
     */
    public void freeCropEditorView(boolean isCancel) {
        if (cropView != null) {
            //保存最终图片
            if (!isCancel) {
                Bitmap cropImageBitmap = cropView.getCroppedImage();
                mCache.remove(PROCESSED + currImagePath);
                mCache.put(PROCESSED + currImagePath, cropImageBitmap);
                if (cropImageBitmap != null && !cropImageBitmap.isRecycled()) {
                    cropImageBitmap.recycle();
                    cropImageBitmap = null;
                    System.gc();
                }
                ll_photo_editor.removeView(cropView);
//            operateArea.setVisibility(View.VISIBLE);
                ll_photo_editor.addView(operateArea);
                cropView = null;
//                operateView.setFlag(true);
                operateView.removeAllItem();
                // 裁剪后贴图，水印，文字等将变得不可操作
                List<ImageObject>  list= list_object.get(currImagePath);
                if(list!=null)
                    list.clear();
                setIs_used_processed(true);//设置此后的编辑图片使用processed+currentpath
                asyncGetImage(new LoadImageCallbackInterface() {
                    @Override
                    public Bitmap loadImage() {
                        return mCache.getAsBitmap(PROCESSED + currImagePath);
                    }
                }, new CacheImageCallbackInterface() {
                    @Override
                    public void onImageLoaded(Bitmap image) {
                        setImageToOperateView(image);
                    }
                });

            } else {
                ll_photo_editor.removeView(cropView);
//            operateArea.setVisibility(View.VISIBLE);
                ll_photo_editor.addView(operateArea);
                cropView = null;
                asyncGetImage(new LoadImageCallbackInterface() {
                    @Override
                    public Bitmap loadImage() {
                        return mCache.getAsBitmap(currImagePath);
                    }
                }, new CacheImageCallbackInterface() {
                    @Override
                    public void onImageLoaded(Bitmap image) {
                        setImageToOperateView(image);
                    }
                });
//                operateView.setFlag(true);
            }

        }
//        operateView.setFlag(true);
    }

    public void initFilterEditorfirstView() {
        if (m1FilterView == null) {
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            m1FilterView = new GPUImageView(this);
            m1FilterView.getGPUImage().setScaleType(GPUImage.ScaleType.CENTER_INSIDE);
            m1FilterView.getGPUImage().setBackgroundColor(0, 0, 0);
            m1FilterView.setLayoutParams(layoutParams);
        }
//    if(tmpFilterView==null)
//    {
//        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
//                ViewGroup.LayoutParams.WRAP_CONTENT,
//                ViewGroup.LayoutParams.WRAP_CONTENT
//        );
//        tmpFilterView = new GPUImageView(this);
//        tmpFilterView.getGPUImage().setScaleType(GPUImage.ScaleType.CENTER_INSIDE);
//        tmpFilterView.getGPUImage().setBackgroundColor(0,0,0);
//        tmpFilterView.setLayoutParams(layoutParams);
//    }
    }

    public void setFilterImage(Bitmap bitmap) {
        int width = operateView.getmWidth();
        int height = operateView.getmHeight();
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                width,
                height
        );
        mFilterView.getGPUImage().setScaleType(GPUImage.ScaleType.CENTER_INSIDE);
        mFilterView.getGPUImage().setBackgroundColor(0, 0, 0);
        mFilterView.setImage(bitmap);
    }

    public final String ORIGBITMAP = "origi_bitmap";

    public void reInitFilterEditorView()
    {

        int vwidth = operateView.getMvwidth();
        int vheight = operateView.getMvheight();
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                vwidth,
                vheight
        );
        mFilterView.getGPUImage().setScaleType(GPUImage.ScaleType.CENTER_INSIDE);
        mFilterView.getGPUImage().setBackgroundColor(0, 0, 0);
        mFilterView.setLayoutParams(layoutParams);
        mFilterView.setImage(mCache.getAsBitmap(ORIGBITMAP));

    }
    /**
     * 初始化滤镜编辑界面
     */
    public void initFilterEditorView() {
        if (mFilterView == null) {
//            mdialog = createLoadingDialog(PhotoEditorActivity.this, "图片加载中");
//            mdialog.show();
            int width = operateView.getmWidth();
            int height = operateView.getmHeight();
            int vwidth = operateView.getMvwidth();
            int vheight = operateView.getMvheight();
            final Bitmap ori = operateView.getRetBmp();
//            mCache.remove(ORIGBITMAP);
//            mCache.put(ORIGBITMAP, ori);
            new Thread() {
                public void run() {
                    mCache.remove(ORIGBITMAP);
                    mCache.put(ORIGBITMAP, ori);
                }
            }.start();
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                    vwidth,
                    vheight
            );
            mFilterView = new GPUImageView(this);
            mFilterView.getGPUImage().setScaleType(GPUImage.ScaleType.CENTER_INSIDE);
            mFilterView.getGPUImage().setBackgroundColor(0, 0, 0);
            mFilterView.setLayoutParams(layoutParams);
            mFilterView.setImage(ori);
            //暂停operateview 刷新线程，释放资源
//            operateView.setFlag(false);

//            operateView.FreeBitmap();
//            List<ImageObject> list = list_object.get(currImagePath);
            ll_photo_editor.addView(mFilterView);
//            operateArea.setVisibility(View.GONE);
//            operateView.setVisibility(View.GONE);
//            ll_photo_editor.removeView(operateArea);
            operateView.FreeGarbageBitmap();
            if(mdialog!=null&&mdialog.isShowing())
            {
                mdialog.dismiss();
                mdialog=null;
            }
            if(operateArea!=null) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ll_photo_editor.removeView(operateArea);
                    }
                }, 500);
            }
        }
    }

    public static boolean is_filtered = false;//滤镜处理后，贴图等不可再编辑

    public void freeFilterEditorView(boolean isCancel) {
        if (mFilterView != null) {
            //保存最终图片
            if (!isCancel) {
                try {
                    Bitmap cropImageBitmap = mFilterView.capture();
                    Rect rect = operateView.getRealSize();
                    int bpw = operateView.getmWidth();
                    int bph = operateView.getmHeight();
                    Bitmap realBitmap = Bitmap.createBitmap(cropImageBitmap, rect.left, rect.top, bpw, bph, null, false);
                    //为了后面拼图使用
                    mCache.remove(PROCESSED + currImagePath);
                    mCache.put(PROCESSED + currImagePath, realBitmap);
                    is_filtered = false;
                    ll_photo_editor.addView(operateArea);
                    operateView.removeAllItem();//滤镜之后，贴图，文字等不可再编辑，所以把贴图文字等删除掉
                    setIs_used_processed(true);//设置后面编辑此图片使用processed+currentpath
                    if (cropImageBitmap != null && !cropImageBitmap.isRecycled()) {
                        cropImageBitmap.recycle();
                        cropImageBitmap = null;
                    }
                    if (cacheBitmap != null && !cacheBitmap.isRecycled()) {
                        cacheBitmap.recycle();
                        cacheBitmap = null;
                    }
                    if (realBitmap != null && !realBitmap.isRecycled()) {
                        realBitmap.recycle();
                        realBitmap = null;
                    }
                    System.gc();
//                    ll_photo_editor.removeView(mFilterView);
//                    mFilterView = null;
                    initImageEditorView();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ll_photo_editor.removeView(mFilterView);
                            mFilterView = null;
                        }
                    }, 500);

                } catch (InterruptedException e) {

                }
            } else {
                is_filtered = false;
//                ll_photo_editor.removeView(mFilterView);
//                mFilterView = null;
                ll_photo_editor.addView(operateArea);
                if (curbmToFilter != null && !curbmToFilter.isRecycled()) {
                    curbmToFilter.recycle();
                    curbmToFilter = null;
                }
                asyncGetImage(new LoadImageCallbackInterface() {
                    @Override
                    public Bitmap loadImage() {
                        return mCache.getAsBitmap(currImagePath);
                    }
                }, new CacheImageCallbackInterface() {
                    @Override
                    public void onImageLoaded(Bitmap image) {
                        setImageToOperateView(image);
                        ll_photo_editor.removeView(mFilterView);
                        mFilterView = null;
                    }
                });
                List<ImageObject> list = list_object.get(currImagePath);
                if (list != null && list.size() > 0) {
                    operateView.setImgLists(list);
                }

//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        ll_photo_editor.removeView(mFilterView);
//                        mFilterView = null;
//                    }
//                }, 200);

            }
            can_filter_index=0;
            if (iv_filter_list != null) {
                int count = iv_filter_list.getChildCount();
                for (int i = 0; i < count; i++) {
                    MyImageView2 mv2 = (MyImageView2) iv_filter_list.getChildAt(0);
                    if (mv2 != null) {
                        Bitmap bitmap = mv2.getmBitmap();
                        if (bitmap != null && !bitmap.isRecycled()) {
                            bitmap.recycle();
                            bitmap = null;
                            iv_filter_list.removeView(mv2);
//                          Log.e("freefiler","free="+i);
                        }

                    }

                }
            }
        }
    }

    /**
     * 动态显示/关闭编辑区域
     *
     * @param isShow
     */
    public void slideToolsArea(final Boolean isShow) {
        if (isShow) {
            if (!isToolsAreaShown()) {

                // Show the panel
                Animation bottomUp = AnimationUtils.loadAnimation(this, R.anim.photo_edit_area_bottom_up);

                ll_edit_area.startAnimation(bottomUp);
                ll_edit_area.setVisibility(View.VISIBLE);
            }
        } else {
            if (isToolsAreaShown()) {
                // Hide the Panel
                Animation bottomDown = AnimationUtils.loadAnimation(this, R.anim.photo_edit_area_bottom_down);
                ll_edit_area.startAnimation(bottomDown);
                ll_edit_area.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 判断是否编辑区域可视
     *
     * @return
     */
    public boolean isToolsAreaShown() {
        return ll_edit_area.getVisibility() == View.VISIBLE;
    }

    public void showEditTools(int layoutId) {
        //设置可视区
        showPhotoEditorText(layoutId == R.id.ll_photo_editor_text || layoutId == R.id.ll_photo_text_tools_fonts
                || layoutId == R.id.ll_photo_text_tools_colors || layoutId == R.id.ll_photo_text_tools_phrases || layoutId == R.id.ll_btn_ziti);
        if (layoutId == R.id.ll_photo_editor_text || layoutId == R.id.ll_photo_text_tools_fonts
                || layoutId == R.id.ll_photo_text_tools_colors || layoutId == R.id.ll_photo_text_tools_phrases ||
                layoutId == R.id.ll_btn_ziti) {
//            showPhotoEditorTextFonts(layoutId == R.id.ll_photo_text_tools_fonts);
            showPhotoEditorTextFonts(layoutId == R.id.ll_btn_ziti);
            showPhotoEditorTextColors(layoutId == R.id.ll_photo_text_tools_colors);
            showPhotoEditorTextPhrases(layoutId == R.id.ll_photo_text_tools_phrases);
        }
        showPhotoEditorStickers(layoutId == R.id.ll_photo_editor_stickers);
        showPhotoEditorWatermarks(layoutId == R.id.ll_photo_editor_watermarks);
        showPhotoEditorFilters(layoutId == R.id.ll_photo_editor_filters);
        showPhotoEditorCrop(layoutId == R.id.ll_photo_editor_crop);
        showShareTools(layoutId == R.id.ll_photo_save);

        slideToolsArea(true);
        if (layoutId == R.id.ll_photo_editor_text || layoutId == R.id.ll_photo_editor_watermarks || layoutId == R.id.ll_photo_editor_stickers) {
            //initImageEditorView();
            //自动添加一个文本编辑
        } else if (layoutId == R.id.ll_photo_editor_crop) {
            initCropEditorView();
        } else if (layoutId == R.id.ll_photo_editor_filters) {
            initFilterEditorView();
        } else if (layoutId == R.id.ll_photo_save) {
            initShareTools();
        }
    }

    //1ms
    public void initTextTools() {
//        if (ll_text_tools_area == null)
        {
            ll_text_tools_area = (LinearLayout) flater.inflate(R.layout.photo_editor_text, null);//图片编辑二级菜单
            if (ll_edit_area.getChildCount() > 0) {
                ll_edit_area.removeAllViews();
            }
            ll_edit_area.addView(ll_text_tools_area);

            ll_text_tools_sub_area = (LinearLayout) findViewById(R.id.ll_photo_edit_text_3l_view);//文字，贴图等的三级菜单container

            View ivCancel = ll_text_tools_area.findViewById(R.id.iv_photo_editor_text_cancel);
            View ivOK = ll_text_tools_area.findViewById(R.id.iv_photo_editor_text_ok);

            View btnFonts = ll_text_tools_area.findViewById(R.id.ll_btn_ziti);
            View btnColors = ll_text_tools_area.findViewById(R.id.ll_btn_yanse);
            View btnPhrases = ll_text_tools_area.findViewById(R.id.ll_btn_changyongyu);
            View btnInput = ll_text_tools_area.findViewById(R.id.ll_btn_wenben);
            ivCancel.setOnClickListener(listener);
            ivOK.setOnClickListener(listener);
            btnFonts.setOnClickListener(listener);
            btnColors.setOnClickListener(listener);
            btnPhrases.setOnClickListener(listener);
            btnInput.setOnClickListener(listener);
        }
    }

    public static boolean is_initTextFonts = false;
    LinearLayout mll_font_list = null;

    public boolean initTextFonts() {

        is_initTextFonts = !is_initTextFonts;
        {
            ll_text_tools_fonts = (LinearLayout) flater.inflate(R.layout.photo_text_tools_fonts, null);//字体选择布局
            if (ll_text_tools_sub_area.getChildCount() > 0) {
                ll_text_tools_sub_area.removeAllViews();
            }
            ll_text_tools_sub_area.addView(ll_text_tools_fonts);//三级菜单container

            // 创建字体列表
            LinearLayout ll_font_list = (LinearLayout) ll_text_tools_fonts.findViewById(R.id.ll_photo_text_tools_font_list);

            if (mll_font_list != null && mll_font_list.getChildCount() > 0) {
                int count = mll_font_list.getChildCount();
                for (int i = 0; i < count; i++) {

                    View view = mll_font_list.getChildAt(0);
                    mll_font_list.removeViewAt(0);
                    ll_font_list.addView(view);
                }

            } else {
                String[] font_names = res.getStringArray(R.array.font_name);

                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                List<Typeface> fonttypelist = AppContext.instance().getFontType();
                for (int i = 0; i < font_names.length; i++) {
                    TextView view = new TextView(this);
                    view.setClickable(true);
                    view.setTypeface(fonttypelist.get(i));
                    view.setTag(fontname[i]);

                    view.setText(font_names[i]);
                    view.setTextSize(res.getDimension(R.dimen.default_editor_text_font_size));
                    view.setGravity(Gravity.LEFT);
                    int padding = res.getDimensionPixelSize(R.dimen.space_5dp);
                    view.setPadding(padding, padding, 0, padding);
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            operateView = listItems.get(currImagePath);
                            defaultFont = ((TextView) v).getTypeface();
                            TextObject object = (TextObject) operateView.getSelected();
                            if (object != null) {
                                if (object.getEditable()) {
                                    operateInput.setVisibility(View.GONE);
                                    object.setEditable(false);
                                }
                                object.setTypeface(defaultFont);
                                operateView.updateView();
                                operateView.updateView();
                            } else {
//                            showTextInput("");
                            }
                        }
                    });
                    view.setLayoutParams(lp);
                    ll_font_list.addView(view);
                }

            }
            mll_font_list = ll_font_list;
            return is_initTextFonts;
        }
//        else {
//            return false;
//        }
    }

    public static boolean is_initTextColor = false;

    public boolean initTextColors() {
        is_initTextColor = !is_initTextColor;
//        if (ll_text_tools_colors == null)

        {
            ll_text_tools_colors = (LinearLayout) flater.inflate(R.layout.photo_text_tools_colors, null);
            if (ll_text_tools_sub_area.getChildCount() > 0)
                ll_text_tools_sub_area.removeAllViews();
            ll_text_tools_sub_area.addView(ll_text_tools_colors);
            // 创建颜色列表
            LinearLayout ll_colors_list = (LinearLayout) ll_text_tools_colors.findViewById(R.id.ll_photo_text_tools_colors_list);
            int[] colors = res.getIntArray(R.array.full_colors);
            int barWidth = res.getDimensionPixelSize(R.dimen.photo_tools_text_colors_item_width);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(barWidth, ViewGroup.LayoutParams.MATCH_PARENT);
            for (int color : colors) {
                ImageView imageView = new ImageView(this);
                imageView.setClickable(true);
                imageView.setBackgroundColor(color);
                imageView.setTag(color);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        ImageOperateView operateView=listItems.get(currImagePath);
                        int color = (int) v.getTag();
                        TextObject object = (TextObject) operateView.getSelected();
                        if (object != null) {
                            if (object.getEditable()) {
                                operateInput.setVisibility(View.GONE);
                                object.setEditable(false);
                            }
                            object.setColor(color);
                            operateView.updateView();
                        }
                    }
                });
                imageView.setLayoutParams(lp);
                ll_colors_list.addView(imageView);
            }
            //创建颜色进度条
            SeekBar alphaBar = (SeekBar) ll_text_tools_colors.findViewById(R.id.ll_photo_text_tools_color_alpha_bar);
            alphaBar.setMax(100);
            alphaBar.setOnSeekBarChangeListener(
                    new SeekBar.OnSeekBarChangeListener() {
                        int mProgress = 0;

                        @Override
                        public void onStopTrackingTouch(SeekBar seekBar) {
                            TextView alphaHint = (TextView) ll_text_tools_colors.findViewById(R.id.ll_photo_text_tools_color_alpha_hint);
                            alphaHint.setText(mProgress + "%");
                            int alpha = 255 * mProgress / 100;
//                            ImageOperateView operateView=listItems.get(currImagePath);
                            TextObject object = (TextObject) operateView.getSelected();
                            if (object != null) {
                                if (object.getEditable()) {
                                    operateInput.setVisibility(View.GONE);
                                    object.setEditable(false);
                                    object.setText(operateInput.getText().toString());
                                }
                                object.setAlpha(alpha);
                                operateView.updateView();
                            }
                        }

                        @Override
                        public void onStartTrackingTouch(SeekBar seekBar) {

                        }

                        @Override
                        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                            mProgress = progress;
                        }
                    }
            );
            return is_initTextColor;
        }
//        else {
//            return false;
//        }
    }

    public static boolean is_initTextPhrase = false;

    public boolean initTextPhrases() {
        is_initTextPhrase = !is_initTextPhrase;
//        if (ll_text_tools_phrases == null)
        {
            ll_text_tools_phrases = (LinearLayout) flater.inflate(R.layout.photo_text_tools_phrases, null);
            if (ll_text_tools_sub_area.getChildCount() > 0)
                ll_text_tools_sub_area.removeAllViews();
            ll_text_tools_sub_area.addView(ll_text_tools_phrases);
            // 创建常用语列表
            LinearLayout ll_phrase_list = (LinearLayout) ll_text_tools_phrases.findViewById(R.id.ll_photo_text_tools_phrase_list);
            String[] font_names = getSharedPreference("cants");
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            for (int i = 0; i < font_names.length; i++) {
                TextView view = new TextView(this);
                view.setClickable(true);
                view.setText(font_names[i]);
                view.setTextSize(res.getDimension(R.dimen.default_editor_text_font_size));
                view.setGravity(Gravity.LEFT);
                int padding = res.getDimensionPixelSize(R.dimen.space_5dp);
                view.setPadding(padding, padding, 0, padding);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView phraseView = (TextView) v;
                        showTextInput(phraseView.getText().toString());
                    }
                });
                view.setLayoutParams(lp);
                ll_phrase_list.addView(view);
            }
            return is_initTextPhrase;
        }
//        else {
//            return false;
//        }
    }

    public String[] getSharedPreference(String key) {
        String regularEx = "爩";
        String[] str = null;

        SharedPreferences sp = getSharedPreferences("profiles", Activity.MODE_PRIVATE);
        String values = sp.getString(key, "");
        str = values.split(regularEx);

        return str;
    }


    public void initShareTools() {
        if (ll_share_area == null) {
            ll_share_area = (LinearLayout) flater.inflate(R.layout.photo_save, null);
            ll_edit_area.addView(ll_share_area);
            TextView tv_btn_retry = (TextView) ll_share_area.findViewById(R.id.tv_btn_retry);
            tv_btn_retry.setOnClickListener(listener);
            TextView tv_btn_backhome = (TextView) ll_share_area.findViewById(R.id.tv_btn_backhome);
            tv_btn_backhome.setOnClickListener(listener);
            LinearLayout ll_share_weixin, ll_share_weibo, ll_share_pengyouquan, ll_share_qqzone;
            ll_share_weixin = (LinearLayout) ll_share_area.findViewById(R.id.ll_share_weixin);
            ll_share_weibo = (LinearLayout) ll_share_area.findViewById(R.id.ll_share_weibo);
            ll_share_pengyouquan = (LinearLayout) ll_share_area.findViewById(R.id.ll_share_pengyouquan);
            ll_share_qqzone = (LinearLayout) ll_share_area.findViewById(R.id.ll_share_qqzone);
            ll_share_weixin.setOnClickListener(sharelistener);
            ll_share_weibo.setOnClickListener(sharelistener);
            ll_share_pengyouquan.setOnClickListener(sharelistener);
            ll_share_qqzone.setOnClickListener(sharelistener);
        }
    }


    View.OnClickListener sharelistener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ll_share_weibo:
                    Toast.makeText(PhotoEditorActivity.this, "分享到weibo", Toast.LENGTH_SHORT).show();
//                    weibo();
                    break;
                case R.id.ll_share_weixin:
                    weixin(SendMessageToWX.Req.WXSceneSession);
                    break;
                case R.id.ll_share_pengyouquan:
                    pengyouquan();
                    break;
                case R.id.ll_share_qqzone:
//                    Toast.makeText(PhotoEditorActivity.this, "分享到qq", Toast.LENGTH_SHORT).show();
//                      qqzone();
                    break;
            }
        }
    };
    //
    IWXAPI api = null;

    private void weixin(int type) {
        String appid = "wx4b3b9f9777c6a7b4";
        api = WXAPIFactory.createWXAPI(PhotoEditorActivity.this, "wx4b3b9f9777c6a7b4");
//            api.registerApp(appid);
//        Bitmap bitmap = BitmapFactory.decodeResource(PhotoEditorActivity.this.getResources(), photos.get(currImagePath).);
        Bitmap bitmap = getBitmapFromDiskCache(currImagePath);
        Matrix matrix = new Matrix();
        matrix.postScale(0.8f, 0.8f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        WXImageObject imgobj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgobj;

        Bitmap thumbimg = Bitmap.createScaledBitmap(resizeBmp, 150, 200, true);
        bitmap.recycle();
        msg.setThumbImage(thumbimg);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = type;


        api.sendReq(req);
//            Bundle bundle = new Bundle();
//            GetMessageFromWX.Resp resp = new GetMessageFromWX.Resp();
//            resp.transaction = new GetMessageFromWX.Req(bundle).transaction;
//            resp.message = msg;
//            api.sendResp(resp);
    }


    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private void weibo() {

    }

    private void pengyouquan() {
        weixin(SendMessageToWX.Req.WXSceneTimeline);
    }

    private void qqzone() {

        String[] piclist = new String[]{"http://gtb.baidu.com/HttpService/get?p=dHlwZT1pbWFnZS9qcGVnJm49dmlzJnQ9YWRpbWcmYz10YjppZyZyPTE0MzY3MTc3MDUsMzg4MjcyMzE2MAAAAA==", "http://img0.imgtn.bdimg.com/it/u=2174076011,1829033089&fm=21&gp=0.jpg"};
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < piclist.length; i++) {
            list.add(piclist[i]);
        }
        //分享类型
        Bundle params = new Bundle();
        Tencent mTencent = Tencent.createInstance("1104761580", PhotoEditorActivity.this);
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "标题");//必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "摘要");//选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, "跳转URL");//必填
//            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, "图片链接ArrayList");
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, list);
//            mTencent.shareToQzone(EditActivity.this, params, new BaseUiListener());
        mTencent.shareToQzone(PhotoEditorActivity.this, params, new IUiListener() {
            @Override
            public void onComplete(Object o) {
                Toast.makeText(PhotoEditorActivity.this, "分享成功，" + o.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(UiError uiError) {
                Toast.makeText(PhotoEditorActivity.this, "分享失败，" + uiError, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(PhotoEditorActivity.this, "分享被取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void getStickerCategoryById(int id) {
        AsyncHttpResponseHandler jhandler = new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    Log.i("c", response.toString());
                    int code = response.getInt("code");
                    String msg = response.getString("msg");
                    Log.i("ImageMap-msg", msg);
                    if (code == 200) {
                        imageArrId = response.getJSONArray("data");
                        mStickersId.clear();
                        for (int i = 0; i < imageArrId.length(); i++) {
                            JSONObject jo = imageArrId.getJSONObject(i);
                            mStickersId.add(jo.getString("img_url"));
                        }
                        mAdapter.setData(mStickersId);
                        grid.setVisibility(View.VISIBLE);
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.i("imageArr", responseString);
            }
        };
        RequestParams requestParams = new RequestParams();
        requestParams.put("id", id);
        AppHttpClient.post(AppConsts.API_STICKER_CATEGORY_GET_ID, requestParams, jhandler);
    }

    public void initStickersTools() {
//        if (ll_stickers_area == null)
        {
            ll_stickers_area = (LinearLayout) flater.inflate(R.layout.photo_editor_stickers, null);
            if (ll_edit_area.getChildCount() > 0) {
                ll_edit_area.removeAllViews();
            }
            ll_edit_area.addView(ll_stickers_area);

            View ivCancel = ll_stickers_area.findViewById(R.id.iv_photo_editor_stickers_cancel);
            View ivOK = ll_stickers_area.findViewById(R.id.iv_photo_editor_stickers_ok);
            ivCancel.setOnClickListener(listener);
            ivOK.setOnClickListener(listener);

            grid = (GridView) ll_stickers_area.findViewById(R.id.works_sticky_grid);

            //获取贴图分类列表
            AsyncHttpResponseHandler jhandler = new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {

                    //屏幕宽度
                    DisplayMetrics dm = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(dm);
                    int screenWidth = dm.widthPixels;
                    try {
                        Log.i("c", response.toString());
                        int code = response.getInt("code");
                        String msg = response.getString("msg");
                        Log.i("ImageMap-msg", msg);
                        if (code == 200) {
                            LinearLayout iv_sticker_list = (LinearLayout) ll_stickers_area.findViewById(R.id.iv_photo_editor_stickers_list);
                            iv_sticker_list.removeAllViews();
//                            int imgHeight = res.getDimensionPixelSize(R.dimen.photo_tools_sticker_list_height);
                            int padding = DimenUtils.dp2px(PhotoEditorActivity.this, 5);
                            int imageNum = 5;
                            int imgPaddingNum = 10;
                            stickerHeight = (screenWidth - imgPaddingNum * padding) / imageNum;
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(stickerHeight, stickerHeight);
                            lp.setMargins(padding, padding, padding, padding);
                            imageArr = response.getJSONArray("data");

                            mStickers.clear();
                            for (int i = 0; i < imageArr.length(); i++) {
                                JSONObject jo = imageArr.getJSONObject(i);
                                mStickers.add(jo.getString("img_url"));
                                mStickers_id.add(jo.getInt("id"));
                            }

                            int max_num = 4;
//                            for (int i = 0; i < mStickers.size() && i < max_num; i++)
                            for (int i = 0; i < mStickers.size(); i++) {
                                final String sticker = mStickers.get(i);
                                final ImageView imgView = new ImageView(PhotoEditorActivity.this);
                                imgView.setClickable(true);
                                final int id = mStickers_id.get(i);
                                imgView.setScaleType(ImageView.ScaleType.FIT_XY);
                                imgView.setTag(sticker);
                                imgView.setBackgroundColor(res.getColor(R.color.default_sticker_item_background));
                                imgView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        getStickerCategoryById(id);
//                                        grid.setVisibility(View.VISIBLE);
//                                        handleImageViewClick((ImageView)v);
                                    }
                                });
                                imgView.setLayoutParams(lp);
                                iv_sticker_list.addView(imgView);

                                Picasso.with(PhotoEditorActivity.this)
                                        .load(sticker)
                                        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                                        .noFade()
                                        .resize(100, 100)
                                        .into(imgView);
                            }

//                            if (mStickers.size() > 5) {
//                                final ImageView imgView = new ImageView(PhotoEditorActivity.this);
//                                imgView.setClickable(true);
//                                imgView.setScaleType(ImageView.ScaleType.FIT_XY);
//                                imgView.setLayoutParams(lp);
//                                iv_sticker_list.addView(imgView);
//                                Picasso.with(PhotoEditorActivity.this)
//                                        .load(R.drawable.genduo)
//                                        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
//                                        .placeholder(R.drawable.genduo)
//                                        .into(imgView);
//
//                                imgView.setOnClickListener(new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View v) {
//                                        grid.setVisibility(grid.getVisibility() == View.VISIBLE?View.INVISIBLE: View.VISIBLE);
//                                    }
//                                });
//                            }
                            initGrid();

                        }
                    } catch (JSONException e) {
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    Log.i("imageArr", responseString);
                }
            };
            AppHttpClient.post(AppConsts.API_STICKER_CATEGORY_GET, jhandler);
        }
    }

    private void handleImageViewClick(ImageView imageView) {
        if (imageView.getDrawable() != null) {
            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
            addImageToPic(bitmap, imageView.getTag().toString());
        }
    }

    private void addImageToPic(Bitmap bitmap, String tag) {
//        ImageOperateView operateView=listItems.get(currImagePath);
        int bw = bitmap.getWidth();
        int bh = bitmap.getHeight();
        Rect r1 = operateView.getRealSize();
        ImageObject obj = operateUtils.getImageObject(bitmap, operateView, 5, r1.centerX(), r1.centerY());
        Bitmap bsrc = obj.getSrcBm();
        int bsrcw = obj.getWidth();
        int bsrch = obj.getHeight();
        if (obj != null) {
            operateView.addItem(obj);
            operateView.getTmpImgLists().add(obj);
            operateView.setOnListener(new ImageOperateView.OperateListener() {
                public void onClick(TextObject tObject) {
//                    Toast.makeText(PhotoEditorActivity.this, "onClick", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onClick(ImageObject object) {

                }

                @Override
                public void onRightTopCornerClick(ImageObject object) {

                }

                public boolean onDelete(ImageObject object) {
//                                                                    Toast.makeText(PhotoEditorActivity.this, "删除掉了", Toast.LENGTH_SHORT).show();
                    return true;
                }

                public void onLostEditable(TextObject object) {

                }

                @Override
                public void onLostEditable(ImageObject object) {

                }
            });
        }
    }

    private LinearLayout iv_filter_list;
    private int filterItem=0;

    public void initFiltersTools() {

//        if (ll_filters_area == null)
        {
            ll_filters_area = (LinearLayout) flater.inflate(R.layout.photo_editor_filters, null);
            if (ll_edit_area.getChildCount() > 0)
                ll_edit_area.removeAllViews();
            ll_edit_area.addView(ll_filters_area);
            //加载滤镜列表
            iv_filter_list = (LinearLayout) ll_filters_area.findViewById(R.id.iv_photo_editor_filter_list);
//            gridWater = (GridView) ll_filters_area.findViewById(R.id.works_water_grid);
            final TextView tvProgress = (TextView) ll_filters_area.findViewById(R.id.progress);
            //屏幕宽度
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenWidth = dm.widthPixels;
            int padding = DimenUtils.dp2px(PhotoEditorActivity.this, 1);
            int imageNum = 7;
            int imgPaddingNum = 5;
            stickerHeight = (screenWidth - imgPaddingNum * padding) / imageNum;
            final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(stickerHeight, stickerHeight);
            lp.setMargins(padding, padding, padding, padding);
            final FilterTools.FilterList lists = FilterTools.getFilterList();
            Bitmap bitmap = ThumbnailUtils.extractThumbnail(operateView.getRetBmp(), stickerHeight, stickerHeight);
            long start = System.currentTimeMillis();
            if (iv_filter_list == null || iv_filter_list.getChildCount() == 0) {
                for (int i = 0; i < lists.count(); i++) {
                    MyImageView2 imgView = new MyImageView2(PhotoEditorActivity.this, FilterTools.getFilterList().names.get(i), i);
//                    imgView.setClickable(true);
                    imgView.setDefaultImageBitmap(bitmap);
                    imgView.setTag(i);
                    if(i==filterItem){
//                        imgView.setAlpha(1f);
                        imgView.showXuanzhong(true);
                    }else {
//                        imgView.setAlpha(0.5f);
                        imgView.showXuanzhong(false);
                    }
                    imgView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int indx = (int) v.getTag();
                            if (indx > can_filter_index)
                                return;
                            ((MyImageView2)(iv_filter_list.getChildAt(filterItem))).showXuanzhong(false);
                            filterItem=indx;
//                            v.setAlpha(1);
                            ((MyImageView2)(iv_filter_list.getChildAt(filterItem))).showXuanzhong(true);
//                            MyImageView2 iv=(MyImageView2)v;
//                            iv.setXuanzhong(true);
                            GPUImageFilter filter = FilterTools.createFilterForType(PhotoEditorActivity.this, FilterTools.getFilterList().filters.get(indx));

                            if (is_press_seekbar) {
                                reInitFilterEditorView();

                            }
                            // 执行滤镜效果
//                            if (mFilter == null || (filter != null && !mFilter.getClass().equals(filter.getClass())))
                            {
                                mFilter = filter;
                                mFilterView.setFilter(filter);
                                mFilterAdjuster = new FilterTools.FilterAdjuster(mFilter);
                            }
                            mFilterView.requestRender();
//                            filterSeekBar.setProgress(100);
                            try {
                                curbmToFilter = mFilterView.capture();//给活动调节条使用
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            is_filtered = true;
                            is_press_seekbar = false;
                        }

                    });
                    imgView.setLayoutParams(lp);

                    iv_filter_list.addView(imgView);
                }

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        for (int j = 0; j < lists.count(); j++) {
                            final MyImageView2 mv2 = (MyImageView2) iv_filter_list.getChildAt(j);
                            GPUImageFilter filter = FilterTools.createFilterForType(PhotoEditorActivity.this, FilterTools.getFilterList().filters.get(j));
                            Bitmap bitmap = mv2.getmBitmap();
                            bitmap = m1FilterView.getImage(bitmap, filter);
                            final Bitmap finalBitmap = bitmap;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mv2.setDefaultImageBitmap(finalBitmap);
                                }
                            });
                            can_filter_index = j;
                        }

                    }
                }).start();
            }
            long end = System.currentTimeMillis();
            Log.e("filter", "time=" + (end - start));
//            initGridWater();

            //创建进度条
            ((SeekBar) ll_filters_area.findViewById(R.id.ll_photo_filters_adjuster)).setOnSeekBarChangeListener(
                    new SeekBar.OnSeekBarChangeListener() {

                        @Override
                        public void onStopTrackingTouch(SeekBar seekBar) {
                            Message message = Message.obtain();
                            message.what = UPDATE_FILTER;
                            handler.sendMessage(message);
                            is_press_seekbar = true;

                        }

                        @Override
                        public void onStartTrackingTouch(SeekBar seekBar) {

                        }

                        @Override
                        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                            mprogress = progress;
                            tvProgress.setText(progress + "%");
                        }
                    }
            );

            View ivCancel = ll_filters_area.findViewById(R.id.iv_photo_editor_filters_cancel);
            View ivOK = ll_filters_area.findViewById(R.id.iv_photo_editor_filters_ok);
            ivCancel.setOnClickListener(listener);
            ivOK.setOnClickListener(listener);

        }

    }

    private boolean is_press_seekbar = false;
    private boolean is_can_filter = false;
    private int can_filter_index = 0;
    int mprogress = 0;
    private Bitmap newbmp = null;
    private int oldwidth;
    private int oldheight;

    private Bitmap toConformBitmap(Bitmap background, Bitmap foreground, int p) {
        if (background == null || foreground == null) {
            return null;
        }
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();


        int bbwith = foreground.getWidth();
        int bbheight = foreground.getHeight();

        if (newbmp == null || (newbmp != null && (oldheight != bgHeight || oldwidth != bgWidth))) {
            if (newbmp != null) {
                if (!newbmp.isRecycled()) {
                    newbmp.recycle();
                    newbmp = null;
                }
            }
            try {
                newbmp = ImageUtils.decodeSampledBitmapFromStream(getBaseContext(), R.drawable.test, bgWidth, bgHeight);
                newbmp = Bitmap.createScaledBitmap(newbmp, bgWidth, bgHeight, true);
                oldwidth = bgWidth;
                oldheight = bgHeight;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
        int neww = newbmp.getWidth();
        int newh = newbmp.getHeight();
        for (int i = 0; i < bgWidth; i++) {
            for (int j = 0; j < bgHeight; j++) {
                int color;
                int bp = background.getPixel(i, j);
                int fp = foreground.getPixel(i, j);
                int bpalp = Color.alpha(bp);


                int r = Color.red(bp) * p / 100 + Color.red(fp) * (100 - p) / 100;
                int g = Color.green(bp) * p / 100 + Color.green(fp) * (100 - p) / 100;
                int b = Color.blue(bp) * p / 100 + Color.blue(fp) * (100 - p) / 100;

                int recolor = Color.argb(bpalp, r, g, b);
                newbmp.setPixel(i, j, recolor);

            }
        }

        return newbmp;
    }

    public void initWatermarksTools() {
//        if (ll_watermarks_area == null)
        {
            ll_watermarks_area = (LinearLayout) flater.inflate(R.layout.photo_editor_watermarks, null);
            if (ll_edit_area.getChildCount() > 0)
                ll_edit_area.removeAllViews();
            ll_edit_area.addView(ll_watermarks_area);

            ll_watermark_list = (ScrollView) ll_watermarks_area.findViewById(R.id.iv_photo_editor_watermark_list_box);

            View ivCancel = ll_watermarks_area.findViewById(R.id.iv_photo_editor_watermarks_cancel);
            View ivOK = ll_watermarks_area.findViewById(R.id.iv_photo_editor_watermarks_ok);
            ivCancel.setOnClickListener(listener);
            ivOK.setOnClickListener(listener);

            LinearLayout iv_wm_area = (LinearLayout) ll_watermarks_area.findViewById(R.id.iv_photo_editor_watermark_area);
            ll_watermark_colors = (LinearLayout) flater.inflate(R.layout.photo_text_tools_colors, null);
            ll_watermark_colors.setVisibility(View.GONE); //默认隐藏
            iv_wm_area.addView(ll_watermark_colors);
            //获取水印列表
            AsyncHttpResponseHandler jhandler = new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    try {
                        Log.i("c", response.toString());
                        int code = response.getInt("code");
                        String msg = response.getString("msg");
                        Log.i("ImageMap-msg", msg);
//                     final ImageOperateView   operateView=listItems.get(currImagePath);
                        if (code == 200) {

//                            ll_watermarks_area = (LinearLayout) flater.inflate(R.layout.photo_editor_watermarks, null);
//                            if(ll_edit_area.getChildCount()>0)
//                                ll_edit_area.removeAllViews();
//                            ll_edit_area.addView(ll_watermarks_area);
//                            ll_watermark_list = (ScrollView) ll_watermarks_area.findViewById(R.id.iv_photo_editor_watermark_list_box);
//
//                            View ivCancel = ll_watermarks_area.findViewById(R.id.iv_photo_editor_watermarks_cancel);
//                            View ivOK = ll_watermarks_area.findViewById(R.id.iv_photo_editor_watermarks_ok);
//                            ivCancel.setOnClickListener(listener);
//                            ivOK.setOnClickListener(listener);

//                            LinearLayout iv_wm_area = (LinearLayout) ll_watermarks_area.findViewById(R.id.iv_photo_editor_watermark_area);
//                            ll_watermark_colors = (LinearLayout) flater.inflate(R.layout.photo_text_tools_colors, null);
//                            ll_watermark_colors.setVisibility(View.GONE); //默认隐藏
//                            iv_wm_area.addView(ll_watermark_colors);

                            // 创建颜色列表
                            LinearLayout ll_colors_list = (LinearLayout) ll_watermark_colors.findViewById(R.id.ll_photo_text_tools_colors_list);
                            int[] colors = res.getIntArray(R.array.full_colors);
                            int barWidth = res.getDimensionPixelSize(R.dimen.photo_tools_text_colors_item_width);
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(barWidth, ViewGroup.LayoutParams.MATCH_PARENT);
                            for (int color : colors) {
                                ImageView imageView = new ImageView(getBaseContext());
                                imageView.setClickable(true);
                                imageView.setBackgroundColor(color);
                                imageView.setTag(color);
                                imageView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        int color = (int) v.getTag();
                                        ImageObject object = operateView.getSelected();
                                        if (object != null) {
                                            object.replaceColor(color);
                                            operateView.updateView();
                                        }
                                    }
                                });
                                imageView.setLayoutParams(lp);
                                ll_colors_list.addView(imageView);
                            }
                            //创建颜色进度条
                            SeekBar alphaBar = (SeekBar) ll_watermark_colors.findViewById(R.id.ll_photo_text_tools_color_alpha_bar);
                            alphaBar.setMax(100);
                            alphaBar.setOnSeekBarChangeListener(
                                    new SeekBar.OnSeekBarChangeListener() {

                                        int mProgress = 0;

                                        @Override
                                        public void onStopTrackingTouch(SeekBar seekBar) {
                                            TextView alphaHint = (TextView) ll_watermark_colors.findViewById(R.id.ll_photo_text_tools_color_alpha_hint);
                                            alphaHint.setText(mProgress + "%");
                                            int alpha = 255 * mProgress / 100;
                                            ImageObject object = operateView.getSelected();
                                            if (object != null) {
                                                object.setImgAlpha(alpha);
                                                operateView.updateView();
                                            }
                                        }

                                        @Override
                                        public void onStartTrackingTouch(SeekBar seekBar) {

                                        }

                                        @Override
                                        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                            mProgress = progress;
                                        }
                                    }
                            );
                            showWaterMarkList(response);
                        } else if (code == 204) {
                            //显示水印提示信息
                            showWaterLimitDialog();
                        }
                    } catch (JSONException e) {
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    Log.i("imageArr", responseString);
                }
            };
            AppHttpClient.get(AppConsts.API_WATERMARK_GET, jhandler);
        }
    }

    private void showWaterMarkList(JSONObject response) throws JSONException {

        LinearLayout iv_wm_list = (LinearLayout) ll_watermarks_area.findViewById(R.id.iv_photo_editor_watermark_list);
        iv_wm_list.removeAllViews();

        int listHeight = res.getDimensionPixelSize(R.dimen.photo_tools_watermark_list_area_height);
        int imgHeight = res.getDimensionPixelSize(R.dimen.photo_tools_watermark_list_height);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, imgHeight);
        int padding = DimenUtils.dp2px(PhotoEditorActivity.this, 5);
        lp.setMargins(0, 0, 0, padding);

        imageArr = response.getJSONArray("data");
        if (imageArr == null) {
            return;
        }
        int maxHeight = imageArr.length() * (imgHeight + padding);
        if (listHeight > maxHeight) {
            ll_watermark_list.getLayoutParams().height = maxHeight;
        } else {
            ll_watermark_list.getLayoutParams().height = listHeight;
        }
//       final ImageOperateView operateView=listItems.get(currImagePath);
        for (int i = 0; i < imageArr.length(); i++) {
            JSONObject jo = imageArr.getJSONObject(i);
            final String sticker = jo.getString("img_url");
            final ImageView imgView = new ImageView(PhotoEditorActivity.this);
            imgView.setClickable(true);
            imgView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            imgView.setTag(sticker);
            imgView.setBackgroundColor(0x80000000);
            imgView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ImageView phraseView = (ImageView) v;
                    String imgUrl = (String) phraseView.getTag();
                    target = new Target() {
                        @Override
                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                            ll_watermark_list.setVisibility(View.GONE);
                            ll_watermark_colors.setVisibility(View.VISIBLE);
                            Rect r1 = operateView.getRealSize();
                            ImageObject obj = operateUtils.getImageObject(bitmap, operateView, 5, r1.centerX(), r1.centerY());
                            if (obj != null) {
                                operateView.addItem(obj);
                                operateView.getTmpImgLists().add(obj);
                                operateView.setOnListener(new ImageOperateView.OperateListener() {
                                    public void onClick(TextObject tObject) {
                                        Log.e("water", "onclicked");
//                                                Toast.makeText(PhotoEditorActivity.this, "onClick", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onClick(ImageObject object) {
                                        if (ll_watermark_colors != null)
                                            ll_watermark_colors.setVisibility(View.VISIBLE);
                                        if (ll_watermark_list != null)
                                            ll_watermark_list.setVisibility(View.GONE);
                                    }

                                    @Override
                                    public void onRightTopCornerClick(ImageObject object) {

                                    }

                                    public boolean onDelete(ImageObject object) {
                                        return true;
                                    }

                                    public void onLostEditable(TextObject object) {

                                    }

                                    @Override
                                    public void onLostEditable(ImageObject object) {
                                        if (ll_watermark_colors != null)
                                            ll_watermark_colors.setVisibility(View.GONE);
                                        if (ll_watermark_list != null)
                                            ll_watermark_list.setVisibility(View.VISIBLE);
                                    }
                                });
                            }
                        }

                        @Override
                        public void onBitmapFailed(Drawable errorDrawable) {

                        }

                        @Override
                        public void onPrepareLoad(Drawable placeHolderDrawable) {

                        }
                    };
                    Picasso.with(PhotoEditorActivity.this)
                            .load(sticker)
                            .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                            .noFade()
                            .resize(250, 250)
                            .into(target);
                }
            });
            imgView.setLayoutParams(lp);
            iv_wm_list.addView(imgView);

            Picasso.with(PhotoEditorActivity.this)
                    .load(sticker)
                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                    .noFade()
                    .resize(250, 250)
                    .into(imgView);
        }
    }

    private void showWaterLimitDialog() {
        String msg = getString(R.string.water_mark_hint);
        new AlertDialog(PhotoEditorActivity.this).builder().setTitle(getString(R.string.dlg_title_hint)).setMsg
                (msg).setPositiveButton(getString(R.string.btn_ok),
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        freeImageEditorView(true);
                        slideToolsArea(false);
                    }
                }).setNegativeButton(getString(R.string.btn_cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                freeImageEditorView(true);
                slideToolsArea(false);

            }
        }).show();
    }

    public void initCropTools() {
//        if (ll_crop_area == null)
        {
            ll_crop_area = (LinearLayout) flater.inflate(R.layout.photo_editor_crop, null);
            if (ll_edit_area.getChildCount() > 0)
                ll_edit_area.removeAllViews();
            ll_edit_area.addView(ll_crop_area);

            View ivCancel = ll_crop_area.findViewById(R.id.iv_photo_editor_crop_cancel);
            View ivOK = ll_crop_area.findViewById(R.id.iv_photo_editor_crop_ok);
            ivCancel.setOnClickListener(listener);
            ivOK.setOnClickListener(listener);
        }
    }

    public void showPhotoEditorText(boolean isShow) {
        if (isShow) {
            initTextTools();
            ll_text_tools_area.setVisibility(View.VISIBLE);//文字编辑二级菜单显示ok，cancel
            //ll_text_tools_sub_area.setVisibility(View.GONE);
        } else {
            if (ll_text_tools_area != null)
                ll_text_tools_area.setVisibility(View.GONE);
        }
    }

    public void SlideOffTextAll(boolean isShow) {
        showPhotoEditorTextFonts(false);
        showPhotoEditorTextColors(false);
        showPhotoEditorTextPhrases(false);
        showPhotoEditorText(false);
    }

    public void showPhotoEditorTextFonts(boolean isShow) {
        if (isShow) {
            boolean isInit = initTextFonts();
            if (!isInit && ll_text_tools_fonts.getVisibility() == View.VISIBLE)
                ll_text_tools_fonts.setVisibility(View.GONE);
            else
                ll_text_tools_fonts.setVisibility(View.VISIBLE);

            ll_text_tools_sub_area.setVisibility(View.VISIBLE);
        } else {
            is_initTextFonts=false;
            if (ll_text_tools_fonts != null)
                ll_text_tools_fonts.setVisibility(View.GONE);
        }
    }

    public void showPhotoEditorTextColors(boolean isShow) {
        if (isShow) {
            boolean isInit = initTextColors();
            if (!isInit && ll_text_tools_colors.getVisibility() == View.VISIBLE)
                ll_text_tools_colors.setVisibility(View.GONE);
            else
                ll_text_tools_colors.setVisibility(View.VISIBLE);

            ll_text_tools_sub_area.setVisibility(View.VISIBLE);
        } else {
            is_initTextColor=false;
            if (ll_text_tools_colors != null)
                ll_text_tools_colors.setVisibility(View.GONE);
        }
    }

    public void showPhotoEditorTextPhrases(boolean isShow) {
        if (isShow) {
            boolean isInit = initTextPhrases();
            if (!isInit && ll_text_tools_phrases.getVisibility() == View.VISIBLE)
                ll_text_tools_phrases.setVisibility(View.GONE);
            else
                ll_text_tools_phrases.setVisibility(View.VISIBLE);

            ll_text_tools_sub_area.setVisibility(View.VISIBLE);
        } else {
            is_initTextPhrase=false;
            if (ll_text_tools_phrases != null)
                ll_text_tools_phrases.setVisibility(View.GONE);
        }
    }

    public void showPhotoEditorStickers(boolean isShow) {
        if (isShow) {
            initStickersTools();
            ll_stickers_area.setVisibility(View.VISIBLE);
            //ll_text_tools_sub_area.setVisibility(View.GONE);
        } else {
            if (ll_stickers_area != null)
                ll_stickers_area.setVisibility(View.GONE);
        }
    }


    public void showShareTools(boolean isShow) {
        if (isShow) {
            initShareTools();
            ll_share_area.setVisibility(View.VISIBLE);
            //ll_text_tools_sub_area.setVisibility(View.GONE);
        } else {
            if (ll_share_area != null)
                ll_share_area.setVisibility(View.GONE);
        }
    }

    public void showPhotoEditorWatermarks(boolean isShow) {
        if (isShow) {
            initWatermarksTools();
            if (ll_watermarks_area != null) {
                ll_watermarks_area.setVisibility(View.VISIBLE);
                if (ll_watermark_list.getVisibility() == View.GONE) {
                    ll_watermark_list.setVisibility(View.VISIBLE);
                    ll_watermark_colors.setVisibility(View.GONE);
                }
            }
        } else {
            if (ll_watermarks_area != null)
                ll_watermarks_area.setVisibility(View.GONE);
        }
    }

    public void showPhotoEditorFilters(boolean isShow) {
        if (isShow) {
            initFiltersTools();
            ll_filters_area.setVisibility(View.VISIBLE);
        } else {
            if (ll_filters_area != null)
                ll_filters_area.setVisibility(View.GONE);
        }
    }

    public void showPhotoEditorCrop(boolean isShow) {
        if (isShow) {
            initCropTools();
            ll_crop_area.setVisibility(View.VISIBLE);
        } else {
            if (ll_crop_area != null)
                ll_crop_area.setVisibility(View.GONE);
        }
    }

    public View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_back:
                    freeFilterEditorView(true);
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    slideToolsArea(false);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            PhotoEditorActivity.this.finish();
                        }
                    },200);
                    finish();
                    break;
                case R.id.tv_PhotoSave:
                    if (mFilterView != null) {
                        Toast.makeText(PhotoEditorActivity.this, "请先保存滤镜效果", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //保存当前的到相机内
//                    freeAllEditorViews(false);
                    slideToolsArea(false);
                    new Thread() {
                        public void run() {
//                            Bitmap bm=null;
//                            if(is_used_processed())
//                                bm=mCache.getAsBitmap(PROCESSED+currImagePath);
//                            else
//                                bm=mCache.getAsBitmap(currImagePath);
                            if (saveImageToGallery(operateView.getRetBmp())) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(PhotoEditorActivity.this, "图片已保存到相册", Toast.LENGTH_SHORT).show();
                                        //分享
                                        if (isToolsAreaShown()) return;
                                        ll_photo_tools.setVisibility(View.GONE);
                                        showEditTools(R.id.ll_photo_save);
                                    }
                                });
                            } else
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(PhotoEditorActivity.this, "图片保存失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                        }
                    }.start();
                    break;

                // Tools
                case R.id.ll_photo_txt_tools:  //文字
                    if (isToolsAreaShown()) return;
                    if (operateView != null)
                        operateView.setIs_can_edit(true);
                    showEditTools(R.id.ll_photo_editor_text);
                    showTextInput("");
                    operateView.updateView();
                    break;
                case R.id.iv_photo_editor_text_cancel: //文字取消
                    ll_edit_area.setVisibility(View.GONE);
//                    slideToolsArea(false);
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    freeImageEditorView(true);
                    operateView.updateView();
                    break;
                case R.id.iv_photo_editor_text_ok: //结束操作
                    freeImageEditorView(false);
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    slideToolsArea(false);
                    operateView.updateView();
                    break;
//                case R.id.btn_photo_editor_text_fonts://字体
                case R.id.ll_btn_ziti://字体
                    showEditTools(R.id.ll_btn_ziti);
                    if (operateView != null)
                        operateView.setIs_can_edit(true);
                    operateView.updateView();
//                    showEditTools(R.id.ll_photo_text_tools_fonts);
                    break;
//                case R.id.btn_photo_editor_text_colors://颜色
                case R.id.ll_btn_yanse://颜色
                    if (operateView != null)
                        operateView.setIs_can_edit(true);
                    showEditTools(R.id.ll_photo_text_tools_colors);
                    operateView.updateView();
                    break;
//                case R.id.btn_photo_editor_text_phrases://常用语
                case R.id.ll_btn_changyongyu://常用语
                    if (operateView != null)
                        operateView.setIs_can_edit(true);
                    showEditTools(R.id.ll_photo_text_tools_phrases);
                    operateView.updateView();
                    break;
//                case R.id.btn_photo_editor_text_input://输入框
                case R.id.ll_btn_wenben://输入框
                    if (operateView != null)
                        operateView.setIs_can_edit(true);
                    showTextInput("");
                    operateView.updateView();
                    break;
                case R.id.ll_photo_tietu_tools: //贴图
                    if (isToolsAreaShown()) return;
                    if (operateView != null)
                        operateView.setIs_can_edit(true);
                    showEditTools(R.id.ll_photo_editor_stickers);
                    operateView.updateView();
                    break;
                case R.id.iv_photo_editor_stickers_cancel:
                    if (grid.isShown())
                        grid.setVisibility(View.GONE);
                    freeImageEditorView(true);
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    slideToolsArea(false);
                    operateView.updateView();
                    break;
                case R.id.iv_photo_editor_stickers_ok:
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    freeImageEditorView(false);
                    slideToolsArea(false);
                    operateView.updateView();
                    break;
                case R.id.ll_photo_filter_tools: //滤镜
                    if (isToolsAreaShown()) return;
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    showEditTools(R.id.ll_photo_editor_filters);
                    break;
                case R.id.iv_photo_editor_filters_cancel:
                    freeFilterEditorView(true);
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    slideToolsArea(false);
                    filterItem=0;
                    break;
                case R.id.iv_photo_editor_filters_ok:
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    slideToolsArea(false);
                    freeFilterEditorView(false);
                    break;
                case R.id.ll_photo_watermark_tools: //水印
                    if (isToolsAreaShown()) return;
                    if (operateView != null)
                        operateView.setIs_can_edit(true);
                    showEditTools(R.id.ll_photo_editor_watermarks);
                    operateView.updateView();
                    break;
                case R.id.iv_photo_editor_watermarks_cancel:
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    freeImageEditorView(true);
                    slideToolsArea(false);
                    operateView.updateView();
                    break;
                case R.id.iv_photo_editor_watermarks_ok:
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    freeImageEditorView(false);
                    slideToolsArea(false);
                    operateView.updateView();
                    break;
                case R.id.ll_photo_crop_tools: // 剪裁
                    if (isToolsAreaShown()) return;
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    showEditTools(R.id.ll_photo_editor_crop);
                    break;
                case R.id.iv_photo_editor_crop_cancel:
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    freeCropEditorView(true);
                    slideToolsArea(false);
                    break;
                case R.id.iv_photo_editor_crop_ok:
                    if (operateView != null)
                        operateView.setIs_can_edit(false);
                    freeCropEditorView(false);
                    slideToolsArea(false);
                    break;
                case R.id.ll_photo_jigsaw_tools: // 拼图
                    if (isToolsAreaShown()) return;
                    Intent intent = new Intent(PhotoEditorActivity.this, JigsawActivity.class);
                    intent.putStringArrayListExtra(JigsawActivity.EXTRA_JIGSAW_IMAGES, photo_paths);
                    operateView.removeAllItem();
                    startActivity(intent);
                    break;
                case R.id.tv_btn_retry:
                    ll_edit_area.setVisibility(View.GONE);
                    ll_photo_tools.setVisibility(View.VISIBLE);
                    slideToolsArea(false);
                    break;
                case R.id.tv_btn_backhome:
                    Intent intent2 = new Intent();
                    intent2.setClass(PhotoEditorActivity.this, MainActivity.class);
                    intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent2);
                    finish();
            }

        }
    };
    public static boolean is_show = true;

    public boolean saveImageToGallery(Bitmap bm) {
        File dir = new File(Environment.getExternalStorageDirectory(), "processImage");
        if (!dir.exists()) {
            dir.mkdir();
        }
        String filename = System.currentTimeMillis() + ".jpg";
        File file = new File(dir, filename);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        //把文件插入系统图库
        try {
            MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), filename, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //更新图库
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        return true;
    }

    /**
     * 保存图片
     *
     * @param bmp
     * @return
     */
    public boolean saveBitmapToDCIM(Bitmap bmp) {
        ContentValues values = new ContentValues(8);
        String newname = DateFormat.format("yyyy-MM-dd kk.mm.ss", System.currentTimeMillis()).toString();
        values.put(MediaStore.Images.Media.TITLE, newname);//名称，随便
        values.put(MediaStore.Images.Media.DISPLAY_NAME, newname);
        values.put(MediaStore.Images.Media.DESCRIPTION, "i美工");//描述，随便
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());//图像的拍摄时间，显示时根据这个排序
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");//默认为jpg格式
        values.put(MediaStore.Images.Media.ORIENTATION, 0);

        final String CAMERA_IMAGE_BUCKET_NAME = "/sdcard/dcim/camera";
        final String CAMERA_IMAGE_BUCKET_ID = String.valueOf(CAMERA_IMAGE_BUCKET_NAME.hashCode());
        File parentFile = new File(CAMERA_IMAGE_BUCKET_NAME);
        String name = parentFile.getName().toLowerCase();

        values.put(MediaStore.Images.ImageColumns.BUCKET_ID, CAMERA_IMAGE_BUCKET_ID);//id
        values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, name);

        // 先得到新的URI
        Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        try {
            //写入数据
            OutputStream outStream = getContentResolver().openOutputStream(uri);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.close();
        } catch (Exception e) {
            Log.e("SaveBitmap", "exception while writing image", e);
            return false;
        }
        return true;
    }

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 800) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public void showTextInput(String text) {
//     ImageOperateView   operateView=listItems.get(currImagePath);
        String input;
        if (!StringUtils.isEmpty(text)) {
            input = text;
        } else {
            input = getResources().getString(R.string.input_text);
        }
        TextObject currObj = (TextObject) operateView.getSelected();
        if (currObj != null) {
            //
            if (currObj.getEditable()) {
                operateInput.setText(input);
            } else {
                if (!StringUtils.isEmpty(text)) {
                    currObj.setText(text);
                } else if (!StringUtils.isEmpty(currObj.getText())) {
                    currObj.setText(currObj.getText());
                } else {
                    currObj.setText(input);
                }
                operateView.updateView();
                currObj.regenerateBitmap();
            }
        } else {
            Rect r1 = operateView.getRealSize();
            final TextObject textObj = operateUtils.getTextObject(input, operateView, 5, r1.centerX(), r1.centerY());
            if (textObj != null) {
                textObj.setColor(defaltFontColor);
                textObj.setTypeface(defaultFont);
                textObj.commit();
                textObj.setPressCount(0);
                textObj.setSelected(true);
                operateView.addItem(textObj);
                operateView.getTmpImgLists().add(textObj);
                operateView.setOnListener(new ImageOperateView.OperateListener() {

                    public void onClick(TextObject tObject) {
                        initEditable(tObject);
                    }

                    @Override
                    public void onClick(ImageObject object) {

                    }

                    public void onLostEditable(TextObject object) {
                        if (operateInput.getVisibility() == View.VISIBLE) {
                            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                                    hideSoftInputFromWindow(
                                            operateInput.getWindowToken(),
                                            0
                                    );
                            operateInput.setVisibility(View.GONE);
                            if (object != null) {
                                String txt = operateInput.getText().toString();
                                if (!StringUtils.isEmpty(txt)) {
                                    object.setText(txt.replace("\n", ""));
                                    object.setPressCount(0);
                                    object.setSelected(false);
                                    object.regenerateBitmap();
                                } else {
                                    object.setText("点击输入文字");
                                    object.setPressCount(0);
                                    object.regenerateBitmap();
                                }
                            }
                        } else {
                            ll_text_tools_sub_area.setVisibility(View.GONE);
//                            SlideOffTextAll(false);
                        }
                    }

                    @Override
                    public void onLostEditable(ImageObject object) {

                    }

                    @Override
                    public void onRightTopCornerClick(ImageObject object) {
                        TextObject obj = (TextObject) object;
                        if (obj.getEditable()) {
                            operateInput.setVisibility(View.GONE);
                            obj.setEditable(false);
                            obj.setText(operateInput.getText().toString());
                        }
                        if (obj.getTextOrientation() == TextObject.TextOrientation.HORIZONTAL) {
                            obj.setTextOrientation(TextObject.TextOrientation.VERTICAL);
                        } else {
                            obj.setTextOrientation(TextObject.TextOrientation.HORIZONTAL);
                        }
                    }

                    public boolean onDelete(ImageObject object) {
                        operateInput.setVisibility(View.GONE);
                        //Toast.makeText(PhotoEditorActivity.this, "删除掉了", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                });
//                operateView.invalidate();
//                initEditable(textObj);
            }
        }
    }

    public void initEditable(TextObject object) {
        if (object != null) {
            if (object.getTextOrientation() == TextObject.TextOrientation.HORIZONTAL) {
                operateInput.setSingleLine(true);
//                operateInput.setText(object.getText());
            } else {
                operateInput.setSingleLine(false);
                String txt = object.getText();
                StringBuffer vText = new StringBuffer();
                for (int i = 0; i < txt.length(); i++) {
                    vText.append(txt.charAt(i));
                    if (i != txt.length())
                        vText.append("\n");
                }
                operateInput.setText(vText.toString());
            }
            operateInput.setWidth(object.getWidth());
            operateInput.setHeight(object.getHeight());
            operateInput.setTypeface(object.getTypeface());
            operateInput.setTextColor(object.getColor());
            operateInput.setTextSize(DisplayUtils.px2sp(PhotoEditorActivity.this, object.getTextSize()));
            operateInput.setX(object.getX() - object.getWidth() / 2);
            operateInput.setY(object.getY() - object.getHeight() / 2);
            operateInput.setRotation(object.getRotation());
            operateInput.setHint("");
            operateInput.setVisibility(View.VISIBLE);
            operateInput.setFocusable(true);
            operateInput.setCursorVisible(true);
            object.setEditable(true);
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public class ImageAdapter extends BaseAdapter {

        private LayoutInflater mInflater;
        private ArrayList<String> data;

        public ImageAdapter(Context context, ArrayList<String> id) {
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            data = id;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ImageView image;
            final int itemIndx = position;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.works_grid_item, parent, false);
            }
            image = ViewHolder.get(convertView, R.id.image);
            image.setPadding(2, 2, 2, 2);
            image.setBackgroundDrawable(PhotoEditorActivity.this.getResources().getDrawable(R.drawable.works_item_bg));
            final String sticker = data.get(position);
            image.setTag(sticker);
            image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    grid.setVisibility(View.INVISIBLE);
                    handleImageViewClick((ImageView) v);
                }
            });
            Picasso.with(PhotoEditorActivity.this)
                    .load(data.get(position)).placeholder(R.drawable.empty_photo)
                    .memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_STORE)
                    .resize(256, 256)
                    .into(image);
            return convertView;
        }

        public void setData(ArrayList<String> sticker) {
            this.data = sticker;
            this.notifyDataSetChanged();
        }
    }

    public class WaterImageAdapter extends BaseAdapter {

        private LayoutInflater mInflater;

        public WaterImageAdapter(Context context) {
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return FilterTools.getFilterList().count();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ImageView image;
            final int itemIndx = position;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.works_grid_item, parent, false);
            }
            image = ViewHolder.get(convertView, R.id.image);
            image.setPadding(2, 2, 2, 2);
            image.setBackgroundDrawable(PhotoEditorActivity.this.getResources().getDrawable(R.drawable.works_item_bg));
            final int resId = FilterTools.getFilterList().resources.get(position);
            image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    gridWater.setVisibility(View.GONE);
                    GPUImageFilter filter = FilterTools.createFilterForType(PhotoEditorActivity.this, FilterTools.getFilterList().filters.get(itemIndx));
                    // 执行滤镜效果
                    if (mFilter == null || (filter != null && !mFilter.getClass().equals(filter.getClass()))) {
                        mFilter = filter;
                        mFilterView.setFilter(mFilter);
                        mFilterAdjuster = new FilterTools.FilterAdjuster(mFilter);

                        ll_filters_area.findViewById(R.id.ll_photo_filters_adjuster).setVisibility(
                                mFilterAdjuster.canAdjust() ? View.VISIBLE : View.GONE
                        );
                    }
                    mFilterView.requestRender();
                }
            });
            Picasso.with(PhotoEditorActivity.this)
                    .load(resId).placeholder(R.drawable.empty_photo)
                    .memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_STORE)
                    .resize(250, 250)
                    .into(image);
            return convertView;
        }

    }


    public static class ViewHolder {

        @SuppressWarnings("unchecked")
        public static <T extends View> T get(View view, int id) {
            SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
            if (viewHolder == null) {
                viewHolder = new SparseArray<>();
                view.setTag(viewHolder);
            }
            View childView = viewHolder.get(id);
            if (childView == null) {
                childView = view.findViewById(id);
                viewHolder.put(id, childView);
            }
            return (T) childView;
        }

    }

}
